package org.xiaojl.xcloud.tools.gateway.filter.error;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**  
 * <p>Title: XcloudErrorFilter</p>  
 *
 * <p>Description:  进行异常统一处理</p>  
 *
 * @author jilong.xiao  
 * @date 2018年4月23日  
 */
//@Component
public class XcloudErrorFilter extends ZuulFilter {
	private static final Logger log = LoggerFactory.getLogger(XcloudErrorFilter.class);

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		Throwable throwable = ctx.getThrowable();
		log.error("异常过滤器:",throwable);
		
		ctx.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
		ctx.setResponseStatusCode(500);// 返回错误码  
		ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ctx.set("error.exception", throwable.getCause());
//        RpcResult result = RpcResult.fail("系统出现异常，请稍后再试", "服务异常", throwable.getLocalizedMessage());
//		FilterKit.setRespBody(ctx,  JsonKit.toJson(result));
//		FilterKit.setFilterFlag(ctx, false);
		
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.ERROR_TYPE;
	}
	@Override
	public int filterOrder() {
		return 0;
	}
	
}
